﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace VeryExtremeArt.Controller
{
    public class AuctionController
    {
        public AuctionedItem AddItemToAuction(int artPieceId, int auctionId)
        {
            AuctionedItem auctionedItem = new AuctionedItem();

            auctionedItem.ArtPieceId = artPieceId;
            auctionedItem.AuctionId = auctionId;
            using (DataBaseDataContext db = new DataBaseDataContext())
            {
                try
                {
                    db.AuctionedItems.InsertOnSubmit(auctionedItem);
                    db.SubmitChanges();
                    return auctionedItem;
                }
                catch (Exception e)
                {

                    return null;
                }
            }
        }
        public List<ArtPiece> GetCatalogue()
        {
            IList<ArtPiece> catalogue = new List<ArtPiece>();
            Auction nextAuction = GetNextAuction();
            using (DataBaseDataContext db = new DataBaseDataContext())
            {
                List<AuctionedItem> auctionedItemList = db.AuctionedItems.Where(ai => ai.AuctionId == nextAuction.Id).ToList();
                List<ArtPiece> artPieceList = new List<ArtPiece>();
                foreach (AuctionedItem item in auctionedItemList)
                {
                    artPieceList.Add(item.ArtPiece);
                }
                return artPieceList;
            }
        }

        public Auction GetNextAuction()
        {
            // TODO implement
            using (DataBaseDataContext db = new DataBaseDataContext())
            {
                try
                {
                    //Auction auction = db.Auctions.FirstOrDefault(a => a.StartDate > DateTime.Now && a.EndDate > DateTime.Now && (a.StartDate.Year <= DateTime.Now.AddYears(1).Year));
                    //IList<AuctionedItem> aiList = auction.AuctionedItems;
                    //db.exe
                    Auction auction = db.Auctions.Include(a => a.AuctionedItems).FirstOrDefault(a => a.StartDate > DateTime.Now && a.EndDate > DateTime.Now && (a.StartDate.Year <= DateTime.Now.AddYears(1).Year));

                    return (Auction)auction;
                }
                catch (Exception e)
                {
                    //TODO 
                    throw e;
                }
            }
        }
    }
}